import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import prisma from '@/lib/prisma'

// 获取单个问题详情
export async function GET(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions)
    if (!session) {
      return NextResponse.json({ message: '未授权' }, { status: 401 })
    }

    const { id } = params

    // 增加问题的浏览量
    await prisma.forumQuestion.update({
      where: { id },
      data: {
        viewCount: {
          increment: 1,
        },
      },
    })

    // 获取问题详情
    const question = await prisma.forumQuestion.findUnique({
      where: { id },
      include: {
        author: {
          select: {
            id: true,
            name: true,
            role: true,
          },
        },
        experiment: {
          select: {
            id: true,
            title: true,
          },
        },
        answers: {
          include: {
            author: {
              select: {
                id: true,
                name: true,
                role: true,
              },
            },
          },
          orderBy: {
            createdAt: 'asc',
          },
        },
      },
    })

    if (!question) {
      return NextResponse.json({ message: '问题不存在' }, { status: 404 })
    }

    return NextResponse.json({ question })
  } catch (error) {
    console.error('获取问题详情失败:', error)
    return NextResponse.json({ message: '服务器错误' }, { status: 500 })
  }
}

// 更新问题
export async function PUT(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions)
    if (!session) {
      return NextResponse.json({ message: '未授权' }, { status: 401 })
    }

    const { id } = params
    const { title, content, isSolved } = await req.json()

    // 检查问题是否存在
    const question = await prisma.forumQuestion.findUnique({
      where: { id },
    })

    if (!question) {
      return NextResponse.json({ message: '问题不存在' }, { status: 404 })
    }

    // 验证权限（只有作者或管理员可以修改问题）
    if (question.authorId !== session.user.id && session.user.role !== 'ADMIN' && session.user.role !== 'TEACHER') {
      return NextResponse.json({ message: '权限不足' }, { status: 403 })
    }

    // 准备更新数据
    const updateData: any = {}
    if (title) updateData.title = title
    if (content) updateData.content = content
    if (isSolved !== undefined) updateData.isSolved = isSolved

    // 更新问题
    const updatedQuestion = await prisma.forumQuestion.update({
      where: { id },
      data: updateData,
      include: {
        author: {
          select: {
            id: true,
            name: true,
            role: true,
          },
        },
        experiment: {
          select: {
            id: true,
            title: true,
          },
        },
      },
    })

    return NextResponse.json({
      message: '问题更新成功',
      question: updatedQuestion,
    })
  } catch (error) {
    console.error('更新问题失败:', error)
    return NextResponse.json({ message: '服务器错误' }, { status: 500 })
  }
}

// 删除问题
export async function DELETE(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions)
    if (!session) {
      return NextResponse.json({ message: '未授权' }, { status: 401 })
    }

    const { id } = params

    // 检查问题是否存在
    const question = await prisma.forumQuestion.findUnique({
      where: { id },
    })

    if (!question) {
      return NextResponse.json({ message: '问题不存在' }, { status: 404 })
    }

    // 验证权限（只有作者或管理员可以删除问题）
    if (question.authorId !== session.user.id && session.user.role !== 'ADMIN' && session.user.role !== 'TEACHER') {
      return NextResponse.json({ message: '权限不足' }, { status: 403 })
    }

    // 删除相关回答
    await prisma.forumAnswer.deleteMany({
      where: { questionId: id },
    })

    // 删除问题
    await prisma.forumQuestion.delete({
      where: { id },
    })

    return NextResponse.json({ message: '问题已删除' })
  } catch (error) {
    console.error('删除问题失败:', error)
    return NextResponse.json({ message: '服务器错误' }, { status: 500 })
  }
} 